﻿import QtQuick 2.15
import QtPositioning 5.15

Item {
    id: _root
    anchors.fill: parent
    property var beginCoordinate: QtPositioning.coordinate()
    property var endCoordinate: QtPositioning.coordinate()
    property var lineDash: [4,4]
    property color lineColor: "crimson"
    property int lineWidth: 2
    property color textColor: "crimson"
    property int textPixelSize: 14
    property bool showDistance: true
    readonly property var mapItem: _root.parent

    Canvas{
        id:myCanvas
        anchors.fill: parent
        onPaint: {
            if(!_root.beginCoordinate.isValid || !_root.endCoordinate.isValid)
                return
            var ctx = getContext("2d")
            ctx.clearRect(0,0,myCanvas.width,myCanvas.height)
            ctx.strokeStyle = _root.lineColor
            ctx.lineWidth = _root.lineWidth
            ctx.setLineDash(_root.lineDash)
            //**绘制虚线
            ctx.beginPath()
            var beginPos = _root.mapItem.fromCoordinate(_root.beginCoordinate,false)
            ctx.moveTo(beginPos.x,beginPos.y)
            var endPos = _root.mapItem.fromCoordinate(_root.endCoordinate,false)
            ctx.lineTo(endPos.x,endPos.y)
            ctx.stroke()
            ctx.save()
            //**绘制文字
            if (showDistance) {
                var azimuth = endCoordinate.azimuthTo(beginCoordinate)
                if(azimuth>=180)
                    azimuth = azimuth - 180
                var distance = endCoordinate.distanceTo(beginCoordinate)
                var text = (distance/1000).toFixed(0)+"Km"
                ctx.fillStyle = _root.textColor
                ctx.font = _root.textPixelSize+"px Arial"
                ctx.textAlign = "center"
                var centerX =  (beginPos.x+endPos.x)/2
                var centerY = (beginPos.y+endPos.y)/2
                ctx.translate(centerX,centerY)
                ctx.rotate(azimuth*Math.PI/180-Math.PI/2)
                ctx.fillText(text,0,-_root.textPixelSize/2)
            }
            ctx.restore()
        }
    }

    onBeginCoordinateChanged: {
        update()
    }
    onEndCoordinateChanged: {
        update()
    }
    onLineDashChanged: {
        update()
    }
    onLineColorChanged: {
        update()
    }
    onLineWidthChanged: {
        update()
    }
    onTextColorChanged: {
        update()
    }
    onTextPixelSizeChanged: {
        update()
    }

    Connections{
        target: _root.mapItem
        function onZoomLevelChanged(){
            update()
        }
        function onVisibleRegionChanged(){
            update()
        }
    }

    function update(){
        myCanvas.requestPaint()
    }
}
